package cn.edu.cdtu.yulei.test_demo.service.impl;

import cn.edu.cdtu.yulei.test_demo.mapper.UserMapper;
import cn.edu.cdtu.yulei.test_demo.model.User;
import cn.edu.cdtu.yulei.test_demo.service.UserService;
import cn.edu.cdtu.yulei.test_demo.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UserServiceImpl implements UserService {
    @Override
    public int insertUser(User user){
        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        String password = plusPassword(user.getPassword());
        user.setPassword(password);
        int i = mapper.insertUser(user);
        session.commit();
        session.close();
        return i;

    }

    @Override
    public User getUserInfo(User user) throws NoSuchAlgorithmException {
        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User userInfo = mapper.getUserInfo(user.getUserName());

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] digest = md5.digest(user.getPassword().getBytes());
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(digest);

        if(encode.equals(userInfo.getPassword())){
            return userInfo;
        }
        return null;
    }

    private String plusPassword(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(password.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }
}
